package com.zhj.network.udp.chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @PackageName:com.zhj.network.udp.chat
 * @ClassName:TalkReceive
 * @auter: 朱慧杰
 * @date:2020/7/21 0021 14:13
 **/
public class TalkReceive implements Runnable {

    DatagramSocket socket = null;

    private int port;
    private String msgFrom;

    TalkReceive(int port, String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        while (true) {

            try {
                byte[] buffer = new byte[1024];

                DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

                socket.receive(packet);  // 阻塞式接收

                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                System.out.println(msgFrom + " : " + receiveData);

                if (receiveData.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        socket.close();
    }
}
